
import axios from "axios";
import { useNavigate } from "react-router-dom";

const baseURL = "http://api.chennick.wang"

//创建axios实例
const http = axios.create({
	baseURL,
	timeout: 10000,
})

//添加请求拦截
http.interceptors.request.use((config) => {
	const token = localStorage.getItem("token") || null
	if (token) {
		config.headers['Authorization'] = token
	}
	return config
}, (error) => {
	//对请求错误做些什么
	console.log(error, 'request-error');
	return Promise.reject(error)
})

//添加响应拦截
http.interceptors.response.use((response) => {
	//2XX范围内的状态码都会触发该函数
	//对响应数据做点什么
	return response;
}, (error) => {
	//超出2xx范围的状态码都会触发该方法
	//对响应错误做点什么
	console.log(error, "response-error");
	const navigate = useNavigate()
	const { response } = error

	let message = ""

	const status = response?.status

	switch (status) {
		case 401:
			message = "token失效,请重新登陆"
			localStorage.removeItem('token');
			navigate('/login')
			break;
		case 403:
			message = "拒绝访问"
			break;
		case 404:
			message = "请求地址错误"
			break;
		case 500:
			message = "账号或密码错误"
			break;
		default:
			message = "网络连接故障"
	}

	console.log(message, "response-error-mag");
	return Promise.reject(error)

})

export default http
